package com.lei.ajax.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lei.ajax.dao.UserDao;
import com.lei.ajax.entity.UserEntityJson;

public class UserDaoImpl implements UserDao {

	@Override
	public List<UserEntityJson> listAll() {
		Connection conn = JDBC.getConn();
		String sql = "select user_name from lei_user";
		PreparedStatement ps = null;
		List<UserEntityJson> list = new ArrayList();
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				int i = 1;
				Long id = rs.getLong(i++);
				String userName = rs.getString(i++);
				list.add(new UserEntityJson(id, userName));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public void add(UserEntityJson userName) {
		Connection conn = JDBC.getConn();
		String sql = "insert into lei_user(user_name)value(?)";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, userName.getUserName());
			ps.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public UserEntityJson getById(String userName) {
		Connection conn = JDBC.getConn();
		String sql = "select id,userName from lei_user where id=?";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
		
			ps.setString(1, userName);
			rs = ps.executeQuery();
			if (rs.next()) {
				int i = 1;
				UserEntityJson userNameJson = new UserEntityJson();
				userNameJson.setId(rs.getLong(i++));
				userNameJson.setUserName(rs.getString(i++));
				return userNameJson;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		JDBC.close(rs, ps, conn);
		return null;
	}

}
